package com.example.practice.utils;

import com.alibaba.fastjson.JSONObject;
import jodd.net.HttpMethod;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.Objects;

/**
 * TODO
 *
 * @author zgq
 * @date 2020/10/21 13:54
 */
public class HttpUrlUtil {
    /**
     * http 请求工具
     *
     * @param requestTye      请求类型 post / get
     * @param requestUrl      请求地址
     * @param requestProperty 链接通道参数
     * @param object          请求参数对象，post 请求时使用:JSON 对象
     * @return 返回 请求链接对象
     */
    public static HttpURLConnection connUrl(String requestTye, String requestUrl, Map<String, String> requestProperty, Object object) {
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            if (StringUtils.isNotBlank(requestTye)) {
                //设置请求方式，默认为GET
                connection.setRequestMethod(requestTye.toUpperCase());
            }
            //设置是否向httpUrlConnection输出，post请求，参数要放在http正文内，需要设为true； 默认情况下是false。
            connection.setDoOutput(true);
            //是否从httpUrlConnection读入，默认情况下是true;
            connection.setDoInput(true);
            //设置 链接参数
            setRequestProperty(connection, requestProperty);
            // post 请求 设置 请求参数
            if (StringUtils.isNotBlank(requestTye) && StringUtils.equalsIgnoreCase(requestTye, HttpMethod.POST.toString())) {
                postMethodSetParams(connection, object);
            }
            return connection;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    /**
     * 设置 链接参数
     *
     * @param connection      HttpURLConnection
     * @param requestProperty Map<String, String>
     */
    private static void setRequestProperty(HttpURLConnection connection, Map<String, String> requestProperty) {
        if (!CollectionUtils.isEmpty(requestProperty)) {
            requestProperty.keySet().forEach(key -> connection.setRequestProperty(key, requestProperty.get(key)));
        } else {
            connection.setRequestProperty("content-type", "application/json");  // 对应传参方式 String string = JSONObject.toJSONString(object)
//            connection.setRequestProperty("content-type", "application/x-www-form-urlencoded");   // 对应传参方式 String string = "gender=男&id=1&name=postUrl1";
        }
    }

    /**
     * post 请求设置 请求参数
     *
     * @param connection HttpURLConnection
     * @param object     Object
     * @throws IOException 抛出异常
     */
    private static void postMethodSetParams(HttpURLConnection connection, Object object) throws IOException {
        if (!Objects.isNull(object)) {
            OutputStream outputStream = connection.getOutputStream();
            String string = JSONObject.toJSONString(object);     // post 对应的 content-type = application/json
//            String string = "gender=男&id=1&name=postUrl1";    // post 对应的 content-type = application/x-www-form-urlencoded
            outputStream.write(string.getBytes());

            outputStream.flush();
            outputStream.close();
        }
    }

    /**
     * 读取 http 请求的返回结果
     *
     * @param inputstream InputStream
     * @return String
     * @throws IOException IOException
     */
    public static String readHttpInputStream(InputStream inputstream) throws IOException {
        StringBuilder sb = new StringBuilder();
        BufferedReader read = new BufferedReader(new InputStreamReader(inputstream));
        String line = null;
        while ((line = read.readLine()) != null) {
            System.out.println(line);
            sb.append(line);
        }
        read.close();
        return sb.toString();
    }
}
